package other.edan.system.k3;


import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.data.model.EdanAccountInformation__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.edan.system.client.EdanK3Utils;
import other.edan.system.utils.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description 同步账户信息
 * @Author 黎炎松
 * 2024-08-29 16:47
 */
@RestApi(baseUrl = "/xsy/edanAccount")
public class SyncEdanAccount implements ScheduleJob, FutureTask {
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步账户信息 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncAccountData();
    }

    /**
     * 手动触发产品同步
     * @param
     * @return
     */
    @RestMapping(value = "/syncK3Product", method = RequestMethod.GET)
    public String syncK3Product() throws AsyncTaskException {
        logger.debug("手动触发产品同步");
        String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
        logger.info(LOGGER_MSG + "异步ID:" + messageId);
        return TfReturnMsgTools.getSuccessResult("Start synchronizing data");
    }


    public static void main(String[] args) throws ApiEntityServiceException {
        new SyncEdanAccount().startSyncAccountData();
    }

    /**
     * 开始同步理邦客户数据
     */
    public String startSyncAccountData() {
        try {
            logger.debug(LOGGER_MSG + "处理开始");

            // 获取理邦账户数据
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("pageSize", "200");
            //paramsMap.put("currency", "EUR");
            //paramsMap.put("StartDate", "2024-08-20 13:48:25");
            //paramsMap.put("EndDate", "2024-08-22 13:48:25");
            logger.debug(LOGGER_MSG + " paramsMap: " + paramsMap);
            // 发送请求获取数据
            ResultBody response = EdanK3Utils.sendGet(paramsMap, EdanK3Utils.GET_EDAN_ACCOUNT_URL, "");
            if (!Objects.equals(response.getCode(), "200")) {
                logger.debug(LOGGER_MSG + "查询账户数据异常: " + response.getMessage());
                return TfReturnMsgTools.getFailResult("Abnormal query of account data: " + response.getMessage());
            }

            // 获取产品数据 判断是否有值
            JSONObject result = (JSONObject) response.getResult();
            List<JSONObject> accountList = JSONObject.parseArray(result.getJSONArray("currencyInfos").toJSONString(), JSONObject.class);
            logger.debug(LOGGER_MSG + "查询返回的数据: " + accountList.size());
            if (accountList.size() <= 0) {
                logger.debug(LOGGER_MSG + "无需要处理的数据");
                return TfReturnMsgTools.getSuccessResult("There are no products that need to be synchronized");
            }

            // 查询CRM系统中已经存在的
            String accountStrs = accountList.stream().map(v -> "'" + v.getString("account") + "'").collect(Collectors.joining(","));
            String sql = String.format("select id,accountNumber__c from edanAccountInformation__c where accountNumber__c in (%s)", accountStrs);
            List<JSONObject> crmAccountList = xoqlService.query(sql).getRecords();
            Map<String, Long> crmAccountMap = crmAccountList.stream().collect(Collectors.toMap(e -> e.getString("accountNumber__c"), e1 -> e1.getLong("id")));
            logger.debug(LOGGER_MSG + "crmAccountMap: " + crmAccountMap);

            // 进行保存
            List<EdanAccountInformation__c> addList = new ArrayList<>();
            List<EdanAccountInformation__c> upList = new ArrayList<>();
            for (JSONObject accountObj : accountList) {
                String account = accountObj.getString("account");

                EdanAccountInformation__c edanAccountInformation = new EdanAccountInformation__c();
                edanAccountInformation.setEntityType(3421947052972484L); // 业务类型
                edanAccountInformation.setCompanyName__c(accountObj.getString("beneficiary")); // 公司名称
                edanAccountInformation.setBankOfDeposit__c(accountObj.getString("bank")); // 开户行
                edanAccountInformation.setBankNumber__c(accountObj.getString("swiftCode")); // 银行卡号
                edanAccountInformation.setTaxpayerIdentificationNumber__c(accountObj.getString("taxpayerNo")); // 纳税人识别号
                edanAccountInformation.setAttribute("currencyText__c", accountObj.getString("currency")); // 币别
                edanAccountInformation.setAddressTelephone__c(accountObj.getString("address")); // 地址
                edanAccountInformation.setRemarks__c(accountObj.getString("note")); // 备注

                if (crmAccountMap.containsKey(account)) {
                    // 编辑
                    edanAccountInformation.setId(crmAccountMap.get(account));
                    upList.add(edanAccountInformation);
                    continue;
                }

                // 新增
                edanAccountInformation.setAccountNumber__c(account); // 账号
                addList.add(edanAccountInformation);
            }

            // 批量新增
            if (addList.size() > 0) {
                logger.debug(LOGGER_MSG + "新增的数据: " + addList.size());
                BatchOperateResult batchOperateResult = HCXObjectService.insertBatch(addList);
                if (!batchOperateResult.getSuccess()) {
                    logger.debug(LOGGER_MSG + "批量新增异常: " + batchOperateResult.getErrorMessage());
                    return TfReturnMsgTools.getFailResult("Add Exception:"  +batchOperateResult.getErrorMessage());
                }
            }

            // 批量修改
            if (upList.size() > 0) {
                logger.debug(LOGGER_MSG + "修改的数据: " + upList.size());
                BatchOperateResult batchOperateResult = HCXObjectService.updateBatch(upList);
                if (!batchOperateResult.getSuccess()) {
                    logger.debug(LOGGER_MSG + "批量修改异常: " + batchOperateResult.getErrorMessage());
                    return TfReturnMsgTools.getFailResult("Modify exceptions:"  +batchOperateResult.getErrorMessage());
                }
            }

            logger.debug(LOGGER_MSG + "处理成功");
            return TfReturnMsgTools.getSuccessResult("Synchronization successful");
        } catch (Exception e) {
            logger.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return TfReturnMsgTools.getFailResult("Synchronization exception:" + e.getMessage());
        }
    }


}
